<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div v-show="visible" class="search-container">
      <el-form ref="queryFormRef" :model="queryFormData" label-suffix=":" :inline="true" @submit.prevent="handleQuery">
        {% for column in columns %}
        {% if column.is_query == 1 %}
        {% set dict_type = column.dict_type %}
        {% set column_comment = column.column_comment if column.column_comment else '' %}
        {% set parentheseIndex = column_comment.find("（") %}
        {% set comment = column_comment[:parentheseIndex] if parentheseIndex != -1 else column_comment %}
        {% if column.html_type == "input" %}
        <el-form-item label="{{ comment }}" prop="{{ column.python_field }}">
          <el-input v-model="queryFormData.{{ column.python_field }}" placeholder="请输入{{ comment }}" clearable />
        </el-form-item>
        {% elif (column.html_type == "select" or column.html_type == "radio") and dict_type != "" %}
        <el-form-item label="{{ comment }}" prop="{{ column.python_field }}">
          <el-select v-model="queryFormData.{{ column.python_field }}" placeholder="请选择{{ comment }}" style="width: 180px" clearable>
            <el-option v-for="dict in dictStore.getDictArray('{{ dict_type }}')" :key="dict.dict_value" :label="dict.dict_label" :value="dict.dict_value" />
          </el-select>
        </el-form-item>
        {% elif (column.html_type == "select" or column.html_type == "radio") and dict_type %}
        <el-form-item label="{{ comment }}" prop="{{ column.python_field }}">
          <el-select v-model="queryFormData.{{ column.python_field }}" placeholder="请选择{{ comment }}" clearable>
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        {% elif column.html_type == "datetime" and column.query_type != "BETWEEN" %}
        <el-form-item label="{{ comment }}" prop="{{ column.python_field }}">
          <el-date-picker v-model="queryFormData.{{ column.python_field }}" type="date" value-format="YYYY-MM-DD" clearable placeholder="请选择{{ comment }}" />
        </el-form-item>
        {% endif %}
        {% endif %}
        {% endfor %}
        <!-- 可选：创建人选择与统一日期范围（展开后显示） -->
        <el-form-item v-if="isExpand" prop="creator" label="创建人">
          <UserTableSelect v-model="queryFormData.creator" @confirm-click="handleConfirm" @clear-click="handleQuery" />
        </el-form-item>
        <el-form-item v-if="isExpand" prop="start_time" label="创建时间">
          <DatePicker v-model="dateRange" @update:model-value="handleDateRangeChange" />
        </el-form-item>
        <el-form-item>
          <el-button v-hasPerm="['{{ module_name }}:{{ business_name }}:query']" type="primary" icon="search" @click="handleQuery">查询</el-button>
          <el-button v-hasPerm="['{{ module_name }}:{{ business_name }}:query']" icon="refresh" @click="handleResetQuery">重置</el-button>
          <template v-if="isExpandable">
            <el-link class="ml-3" type="primary" underline="never" @click="isExpand = !isExpand">
            {{ '{{' }} isExpand ? "收起" : "展开" {{ '}}' }}
              <el-icon>
                <template v-if="isExpand">
                  <ArrowUp />
                </template>
                <template v-else>
                  <ArrowDown />
                </template>
              </el-icon>
            </el-link>
          </template>
        </el-form-item>
      </el-form>
    </div>

    <!-- 内容区域 -->
    <el-card shadow="hover" class="data-table">
      <template #header>
        <div class="card-header">
          <span>
            <el-tooltip content="{{ function_name }}列表">
              <QuestionFilled class="w-4 h-4 mx-1" />
            </el-tooltip>
            {{ function_name }}列表
          </span>
        </div>
      </template>

      <!-- 功能区域 -->
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--left">
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-button v-hasPerm="['{{ module_name }}:{{ business_name }}:create']" type="success" icon="plus" @click="handleOpenDialog('create')">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-hasPerm="['{{ module_name }}:{{ business_name }}:delete']" type="danger" icon="delete" :disabled="selectIds.length === 0" @click="handleDelete(selectIds)">批量删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-dropdown v-hasPerm="['{{ module_name }}:{{ business_name }}:batch']" trigger="click">
                <el-button type="default" :disabled="selectIds.length === 0" icon="ArrowDown">更多</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item icon="Check" @click="handleMoreClick(true)">批量启用</el-dropdown-item>
                    <el-dropdown-item icon="CircleClose" @click="handleMoreClick(false)">批量停用</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-col>
          </el-row>
        </div>
        <div class="data-table__toolbar--right">
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-tooltip content="导入">
                <el-button v-hasPerm="['{{ module_name }}:{{ business_name }}:import']" type="success" icon="upload" circle @click="handleOpenImportDialog" />
              </el-tooltip>
            </el-col>
            <el-col :span="1.5">
              <el-tooltip content="导出">
                <el-button v-hasPerm="['{{ module_name }}:{{ business_name }}:export']" type="warning" icon="download" circle @click="handleOpenExportsModal" />
              </el-tooltip>
            </el-col>
            <el-col :span="1.5">
              <el-tooltip content="搜索显示/隐藏">
                <el-button v-hasPerm="['*:*:*']" type="info" icon="search" circle @click="visible = !visible" />
              </el-tooltip>
            </el-col>
            <el-col :span="1.5">
              <el-tooltip content="刷新">
                <el-button v-hasPerm="['{{ module_name }}:{{ business_name }}:refresh']" type="primary" icon="refresh" circle @click="handleRefresh" />
              </el-tooltip>
            </el-col>
            <el-col :span="1.5">
              <el-popover placement="bottom" trigger="click">
                <template #reference>
                  <el-button type="danger" icon="operation" circle></el-button>
                </template>
                <el-scrollbar max-height="350px">
                  <template v-for="column in tableColumns" :key="column.prop">
                    <el-checkbox v-if="column.prop" v-model="column.show" :label="column.label" />
                  </template>
                </el-scrollbar>
              </el-popover>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageTableData"
        highlight-current-row
        class="data-table__content"
        :height="450"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <template #empty>
          <el-empty :image-size="80" description="暂无数据" />
        </template>
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'selection')?.show" type="selection" min-width="55" align="center" />
        <el-table-column v-if="tableColumns.find((col) => col.prop === 'index')?.show" fixed label="序号" min-width="60">
          <template #default="scope">
           {{ '{{' }} (queryFormData.page_no - 1) * queryFormData.page_size + scope.$index + 1 {{ '}}' }}
          </template>
        </el-table-column>
        {% for column in columns %}
        {% set python_field = column.python_field %}
        {% set column_comment = column.column_comment if column.column_comment else '' %}
        {% set parentheseIndex = column_comment.find("（") %}
        {% set comment = column_comment[:parentheseIndex] if parentheseIndex != -1 else column_comment %}
        {% if column.is_list == 1 %}
        <el-table-column v-if="tableColumns.find((col) => col.prop === '{{ python_field }}')?.show" label="{{ comment }}" prop="{{ python_field }}" min-width="140">
        {% if python_field == "status" %}
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'info'">{{ '{{' }} scope.row.status ? '启用' : '停用' {{ '}}' }}</el-tag>
          </template>
        {% elif python_field == "creator" %}
          <template #default="scope">
            <el-tag>{{ '{{' }} scope.row.creator?.name {{ '}}' }}</el-tag>
          </template>
        {% endif %}
        </el-table-column>
        {% endif %}
        {% endfor %}
        <el-table-column v-if="tableColumns.find(col => col.prop === 'operation')?.show" fixed="right" label="操作" align="center" min-width="180">
          <template #default="scope">
            <el-button v-hasPerm="['{{ module_name }}:{{ business_name }}:detail']" type="info" size="small" link icon="document" @click="handleOpenDialog('detail', scope.row.id)">详情</el-button>
            <el-button v-hasPerm="['{{ module_name }}:{{ business_name }}:update']" type="primary" size="small" link icon="edit" @click="handleOpenDialog('update', scope.row.id)">编辑</el-button>
            <el-button v-hasPerm="['{{ module_name }}:{{ business_name }}:delete']" type="danger" size="small" link icon="delete" @click="handleDelete([scope.row.id])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <template #footer>
        <pagination v-model:total="total" v-model:page="queryFormData.page_no" v-model:limit="queryFormData.page_size" @pagination="loadingData" />
      </template>
    </el-card>

    <!-- 弹窗区域 -->
    <el-dialog v-model="dialogVisible.visible" :title="dialogVisible.title" @close="handleCloseDialog">
      <!-- 详情 -->
      <template v-if="dialogVisible.type === 'detail'">
        <el-descriptions :column="4" border>
          {% for column in columns %}
            {% set python_field = column.python_field %}
            {% set column_comment = column.column_comment if column.column_comment else '' %}
            {% set parentheseIndex = column_comment.find("（") %}
            {% set comment = column_comment[:parentheseIndex] if parentheseIndex != -1 else column_comment %}
            <el-descriptions-item label="{{ comment }}" :span="2">
              {{ '{' }}{{ '{' }} detailFormData.{{ python_field }} {{ '}' }}{{ '}' }}
            </el-descriptions-item>
          {% endfor %}
        </el-descriptions>
      </template>
      <!-- 新增、编辑表单 -->
      <template v-else>
        <el-form ref="dataFormRef" :model="formData" :rules="rules" label-suffix=":" label-width="auto" label-position="right">
          {% for column in columns %}
          {% if column.is_insert == 1 or column.is_edit == 1 %}
          {% set dict_type = column.dict_type %}
          {% set column_comment = column.column_comment if column.column_comment else '' %}
          {% set parentheseIndex = column_comment.find("（") %}
          {% set comment = column_comment[:parentheseIndex] if parentheseIndex != -1 else column_comment %}
          {% set required = 'true' if column.is_nullable == '1' else 'false' %}
          {% if column.python_field == "status" %}
          <el-form-item label="状态" prop="status" :required="true">
            <el-radio-group v-model="formData.status">
              <el-radio :value="true">启用</el-radio>
              <el-radio :value="false">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          {% elif column.html_type == "input" %}
          <el-form-item label="{{ comment }}" prop="{{ column.python_field }}" :required="{{ required }}">
            <el-input v-model="formData.{{ column.python_field }}" placeholder="请输入{{ comment }}" />
          </el-form-item>
          {% elif column.html_type == "textarea" %}
          <el-form-item label="{{ comment }}" prop="{{ column.python_field }}" :required="{{ required }}">
            <el-input v-model="formData.{{ column.python_field }}" type="textarea" placeholder="请输入{{ comment }}" rows="4" />
          </el-form-item>
          {% elif (column.html_type == "select" or column.html_type == "radio") and dict_type != "" %}
          <el-form-item label="{{ comment }}" prop="{{ column.python_field }}" :required="{{ required }}">
            <el-select v-model="formData.{{ column.python_field }}" placeholder="请选择{{ comment }}">
              <el-option v-for="dict in dictStore.getDictArray('{{ dict_type }}')" :key="dict.dict_value" :label="dict.dict_label" :value="dict.dict_value" />
            </el-select>
          </el-form-item>
          {% elif (column.html_type == "select" or column.html_type == "radio") and dict_type %}
          <el-form-item label="{{ comment }}" prop="{{ column.python_field }}" :required="{{ required }}">
            <el-select v-model="formData.{{ column.python_field }}" placeholder="请选择{{ comment }}">
              <el-option label="请选择字典生成" value="" />
            </el-select>
          </el-form-item>
          {% elif column.html_type == "date" %}
          <el-form-item label="{{ comment }}" prop="{{ column.python_field }}" :required="{{ required }}">
            <el-date-picker v-model="formData.{{ column.python_field }}" type="date" value-format="YYYY-MM-DD" placeholder="请选择{{ comment }}" />
          </el-form-item>
          {% elif column.html_type == "datetime" %}
          <el-form-item label="{{ comment }}" prop="{{ column.python_field }}" :required="{{ required }}">
            <el-date-picker v-model="formData.{{ column.python_field }}" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择{{ comment }}" />
          </el-form-item>
          {% elif column.html_type == "checkbox" %}
          <el-form-item label="{{ comment }}" prop="{{ column.python_field }}">
            <el-checkbox v-model="formData.{{ column.python_field }}">{{ comment }}</el-checkbox>
          </el-form-item>
          {% elif column.html_type == "imageUpload" %}
          <el-form-item label="{{ comment }}" prop="{{ column.python_field }}">
            <SingleImageUpload v-model="formData.{{ column.python_field }}" />
          </el-form-item>
          {% endif %}
          {% endif %}
          {% endfor %}
        </el-form>
      </template>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button v-if="dialogVisible.type !== 'detail'" v-hasPerm="['{{ module_name }}:{{ business_name }}:submit']" type="primary" @click="handleSubmit">确定</el-button>
          <el-button v-else v-hasPerm="['{{ module_name }}:{{ business_name }}:detail']" type="primary" @click="handleCloseDialog">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 导入弹窗 -->
    <ImportModal 
      v-model="importDialogVisible" 
      :content-config="curdContentConfig"
      @upload="handleUpload" 
    />

    <!-- 导出弹窗 -->
    <ExportModal 
      v-model="exportsDialogVisible"
      :content-config="curdContentConfig"
      :query-params="queryFormData"
      :page-data="pageTableData"
      :selection-data="selectionRows"
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "{{ class_name }}",
  inheritAttrs: false,
});
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ResultEnum } from '@/enums/api/result.enum'
import { QuestionFilled, ArrowUp, ArrowDown, Check, CircleClose } from '@element-plus/icons-vue'
import { formatToDateTime } from '@/utils/dateUtil'
import {{ class_name }}API, { {{ class_name }}PageQuery, {{ class_name }}Table, {{ class_name }}Form } from '@/api/{{ module_name }}/{{ business_name }}'
import { useDictStore } from '@/store/index'
import SingleImageUpload from '@/components/Upload/SingleImageUpload.vue'
import ImportModal from '@/components/CURD/ImportModal.vue'
import ExportModal from '@/components/CURD/ExportModal.vue'
import DatePicker from '@/components/DatePicker/index.vue'
import type { IContentConfig } from '@/components/CURD/types'

const visible = ref(true)
const isExpand = ref(false)
const isExpandable = ref(true)

const queryFormRef = ref()
const dataFormRef = ref()
const total = ref(0)
const selectIds = ref<number[]>([])
const selectionRows = ref<{{ class_name }}Table[]>([]);
const loading = ref(false)

// 字典仓库与需要加载的字典类型
const dictStore = useDictStore()
const dictTypes = [
  {% for column in columns %}
  {% if column.dict_type %}
  '{{ column.dict_type }}',
  {% endif %}
  {% endfor %}
]

// 分页表单
const pageTableData = ref<{{ class_name }}Table[]>([]);

// 表格列配置（根据列生成，可显隐）
const tableColumns = ref([
  { prop: 'selection', label: '选择框', show: true },
  { prop: 'index', label: '序号', show: true },
  {% for column in columns %}
  {% if column.is_list == 1 %}
  { prop: '{{ column.python_field }}', label: '{{ column.column_comment or column.python_field }}', show: true },
  {% endif %}
  {% endfor %}
  { prop: 'operation', label: '操作', show: true }
])

// 导出列（不含选择/序号/操作）
const exportColumns = [
  {% for column in columns %}
  {% if column.is_list == 1 %}
  { prop: '{{ column.python_field }}', label: '{{ column.column_comment or column.python_field }}' },
  {% endif %}
  {% endfor %}
]

// 导入/导出配置
const curdContentConfig = {
  permPrefix: '{{ module_name }}:{{ business_name }}',
  cols: exportColumns as any,
  importTemplate: () => {{ class_name }}API.downloadTemplate{{ class_name }}(),
  exportsAction: async (params: any) => {
    const query: any = { ...params };
    if (typeof query.status === 'string') {
      query.status = query.status === 'true';
    }
    query.page_no = 1;
    query.page_size = 9999;
    const all: any[] = [];
    while (true) {
      const res = await {{ class_name }}API.list{{ class_name }}(query)
      const items = res.data?.data?.items || []
      const total = res.data?.data?.total || 0
      all.push(...items)
      if (all.length >= total || items.length === 0) break
      query.page_no += 1
    }
    return all;
  },
} as unknown as IContentConfig

// 弹窗状态
const dialogVisible = reactive({
  title: '',
  visible: false,
  type: 'create', // 'create' | 'update' | 'detail'
})

// 编辑表单
const formData = reactive<{{ class_name }}Form>({
  id: undefined,
  {% for column in columns %}
  {% if column.is_insert == 1 or column.is_edit == 1 %}
  {{ column.python_field }}: undefined,
  {% endif %}
  {% endfor %}
})

// 定义初始表单数据常量
const initialFormData: {{ class_name }}Form = {
  id: undefined,
  {% for column in columns %}
  {% if column.is_insert == 1 or column.is_edit == 1 %}
  {{ column.python_field }}: {{ 'true' if column.python_field == 'status' else ('' if column.html_type == 'textarea' else 'undefined') }},
  {% endif %}
  {% endfor %}
}

// 重置表单
async function resetForm() {
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
  }
  // 完全重置 formData 为初始状态
  Object.assign(formData, initialFormData);
}

// 表单验证规则（必填项按 is_nullable 生成）
const rules = reactive({
  {% for column in columns %}
  {% if column.is_insert == 1 or column.is_edit == 1 %}
  {% set required = 'true' if column.is_nullable == 1 else 'false' %}
  {{ column.python_field }}: [
    { required: {{ required }}, message: '请输入{{ column.column_comment or column.python_field }}', trigger: 'blur' },
  ],
  {% endif %}
  {% endfor %}
})

// 详情表单
const detailFormData = ref<{{ class_name }}Table>({});


// 统一日期范围
const dateRange = ref<[Date, Date] | []>([]);
function handleDateRangeChange(range: [Date, Date]) {
  dateRange.value = range;
  if (range && range.length === 2) {
    queryFormData.start_time = formatToDateTime(range[0]);
    queryFormData.end_time = formatToDateTime(range[1]);
  } else {
    queryFormData.start_time = undefined;
    queryFormData.end_time = undefined;
  }
}

// 查询参数
const queryFormData = reactive<{{ class_name }}PageQuery>({
  page_no: 1,
  page_size: 10,
  {% for column in columns %}
  {% if column.is_query == 1 and column.query_type != "BETWEEN" %}
  {{ column.python_field }}: undefined,
  {% endif %}
  {% endfor %}
  start_time: undefined,
  end_time: undefined,
  creator: undefined,
})

// 加载表格数据
async function loadingData() {
  loading.value = true;
  try {
    const response = await {{ class_name }}API.list{{ class_name }}(queryFormData);
    pageTableData.value = response.data.data.items;
    total.value = response.data.data.total;
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
}

// 查询（重置页码后获取数据）
async function handleQuery() {
  queryFormData.page_no = 1;
  loadingData();
}

// 选择创建人后触发查询
function handleConfirm() {
  handleQuery()
}

// 重置查询
async function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryFormData.page_no = 1;
  dateRange.value = [];
  queryFormData.start_time = undefined;
  queryFormData.end_time = undefined;
  loadingData();
}

// 行复选框选中项变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item: any) => item.id)
  selectionRows.value = selection
}

// 关闭弹窗
async function handleCloseDialog() {
  dialogVisible.visible = false;
  resetForm();
}

// 打开弹窗
async function handleOpenDialog(type: 'create' | 'update' | 'detail', id?: number) {
  dialogVisible.type = type
  if (id) {
    const response = await {{ class_name }}API.detail{{ class_name }}(id);
    if (type === 'detail') {
      dialogVisible.title = '详情';
      Object.assign(detailFormData.value, response.data.data);
    } else if (type === 'update') {
      dialogVisible.title = '修改';
      Object.assign(formData, response.data.data);
    }
  } else {
    dialogVisible.title = '新增{{ function_name }}';
    formData.id = undefined;
  }
  dialogVisible.visible = true;
}

// 提交表单
async function handleSubmit() {
  dataFormRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true
      try {
        const id = formData.id
        if (id) {
          await {{ class_name }}API.update{{ class_name }}(id, { id, ...formData });
          dialogVisible.visible = false;
          resetForm();
          handleCloseDialog();
          handleResetQuery();
        } else {
          await {{ class_name }}API.create{{ class_name }}(formData);
          dialogVisible.visible = false;
          resetForm();
          handleCloseDialog();
          handleResetQuery();
        }
      } catch (error) {
        console.error(error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除、批量删除
async function handleDelete(ids: number[]) {
  ElMessageBox.confirm('确认删除该项数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        loading.value = true;
        await {{ class_name }}API.delete{{ class_name }}(ids);
        handleResetQuery()
      } catch (error) {
        console.error(error)
      } finally {
        loading.value = false
      }
    })
    .catch(() => {
      ElMessageBox.close()
    })
}

// 批量启用/停用
async function handleMoreClick(status: boolean) {
  if (selectIds.value.length) {
    ElMessageBox.confirm(`确认${status ? '启用' : '停用'}该项数据?`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      try {
        loading.value = true
        await {{ class_name }}API.batchAvailable{{ class_name }}({ ids: selectIds.value, status });
        handleResetQuery()
      } catch (error) {
        console.error(error)
      } finally {
        loading.value = false
      }
    }).catch(() => {
      ElMessageBox.close()
    })
  }
}

// 导入弹窗显示状态
const importDialogVisible = ref(false)
// 导出弹窗显示状态
const exportsDialogVisible = ref(false)

// 打开导入弹窗
function handleOpenImportDialog() {
  importDialogVisible.value = true
}
// 打开导出弹窗
function handleOpenExportsModal() {
  exportsDialogVisible.value = true
}

// 处理上传
const handleUpload = async (formData: FormData) => {
  try {
    const response = await {{ class_name }}API.import{{ class_name }}(formData);
    if (response.data.code === ResultEnum.SUCCESS) {
      ElMessage.success(`${response.data.msg}，${response.data.data}`)
      importDialogVisible.value = false
      await handleQuery()
    }
  } catch (error) {
    console.error(error)
  }
}

// 列表刷新
async function handleRefresh() {
  await loadingData()
}

onMounted(async () => {
  // 预加载字典数据
  if (dictTypes.length > 0) {
    await dictStore.getDict(dictTypes)
  }
  loadingData()
})
</script>

<style lang="scss" scoped></style>
